package com.blast.manager.delay.presenter

import com.blast.manager.delay.DelayActivity
import com.blast.manager.delay.event.KeyDownEvent
import com.wxl.common.AppContext
import com.wxl.common.bean.ScanLeiGuanBean
import com.wxl.common.life.LifecycleManager
import com.wxl.common.room.entity.LeiGuanEntity
import com.wxl.common.serialport.*
import com.wxl.common.util.Toll
import com.wxl.common.wiget.ProgressUpdatePop


/**
 * 在线导入
 */
class OnlineImportPresenter : AbsDelayPresenter() {

    val mKeyDownEvent = KeyDownEvent()

    var mDetonatorMaxNumLimit = 0 //最大可组网数

    var mCurrentDetonatorNum = 0

    var mDetonatorTotalNum = 0

    var scanProgress = 0

    var mProgressUpdatePop:ProgressUpdatePop?=null

    override fun onDelayCreated(vararg args: Any) {
        mDetonatorMaxNumLimit = AppContext.appContext.getLeiGuanMaxNum()
    }

    /**
     * 开始导入
     */
    fun startImport() {

        mCurrentDetonatorNum  = 0
        mDetonatorTotalNum = 0
        scanProgress = 0

        CJQUpdateModel.isPauseReceive = true

        mProgressUpdatePop =  ProgressUpdatePop.show(context)

        updateProgress(0, "正在清除控制板数据...")

        SerialPortManager.cancelIntervalWork()
        mKeyDownEvent.isCanBack = false
        LifecycleManager.manager.refreshLiveData(mKeyDownEvent)

        Serials.registerSingleStartHexSerial(CmdCode.KZB_CLEAR_STATE_OK_ASK, object : Serial() {
            override fun loadReceiveData(data: String) {
                (context as DelayActivity).addLog("在线扫描","清除控制板数据")
                onScanControlData()
            }
        })
        Serials.registerSingleStartHexSerial(CmdCode.KZB_CLEAR_STATE_E_ASK, object : Serial() {
            override fun loadReceiveData(data: String) {
                openKeyDownEvent()
                (context as DelayActivity).addLog("在线扫描","清除控制板数据失败")
                updateProgress(-1, "清除控制板数据失败...")
            }
        })
        SerialPortManager.send(CmdCode.KZB_CLEAR_STATE_CMD)
    }


    private fun updateProgress(p: Int, sub: String) {
        if(mProgressUpdatePop != null && mProgressUpdatePop!!.isShow) {
            ProgressUpdatePop.updateProgress(mProgressUpdatePop!!, p, sub, "在线扫描", mDetonatorTotalNum + 2)
        }
    }

    /**
     * 清除控制板数据成功, 扫描控制板雷管信息
     */
    private fun onScanControlData() {
        updateProgress(0, "正在扫描控制板雷管信息...")
        Serials.registerSingleStartHexSerial(CmdCode.KZB_SCAN_LG_OK_ASK, object : Serial() {
            override fun loadReceiveData(data: String) {
                scanProgress = 0
                (context as DelayActivity).addLog("在线扫描",0,"扫描控制板数据")
                onQueryControlLgData()
            }
        })
        Serials.registerSingleStartHexSerial(CmdCode.KZB_SCAN_LG_E_ASK, object : Serial() {
            override fun loadReceiveData(data: String) {
                openKeyDownEvent()
                updateProgress(-1, "扫描控制板雷管信息失败...")
            }
        })
        //发送扫描指令
        SerialPortManager.send(CmdCode.KZB_SCAN_LG_CMD)
    }


    /**
     * 查询控制板雷管信息
     */
    private fun onQueryControlLgData() {
        Serials.registerSingleStartHexSerial(CmdCode.KZB_QUERY_LG_INFO_OK_ASK, object : Serial() {
            override fun loadReceiveData(data: String) {
                onParseScanControlData(data)
            }
        })
        SerialPortManager.send(CmdCode.KZB_QUERY_LG_INFO_CMD)
    }

    /**
     * 解析扫描出来的数据
     */
    private fun onParseScanControlData(data: String) {
        if (data.length > 30) {
            val result = ScanLeiGuanBean.parse(data)
            //scanProgress ++
            //stateCode 在线雷管扫描状态 0 正常，1 上电失败，2 电流异常， 3 雷管数据已满， 4 未扫描到雷管，数量数量为0， 5 通信电压异常
            ProgressUpdatePop.updateProgress( if(result.progress < 96) result.progress else 96,"扫描控制板雷管信息...", "在线扫描", 100)
            if (result.progress < 100) {
                if (result.stateCode == 0) {
                    onQueryControlLgData()
                } else {
                    openKeyDownEvent()
                    updateProgress(-1, "扫描控制板雷管信息失败(code:${result.stateCode})...")
                }
            } else {
                if (result.stateCode == 0) {
                    (context as DelayActivity).addLog("在线扫描",0,"读控制板数据")
                    onReadControlData()
                } else {
                    openKeyDownEvent()
                    (context as DelayActivity).addLog("在线扫描",0,"扫描控制板雷管信息失败(code:${result.stateCode})")
                    updateProgress(-1, "扫描控制板雷管信息失败(code:${result.stateCode})...")
                }
            }
        } else {
            updateProgress(0, "请接入雷管...")
        }

    }


    /**
     * 扫描完成，读取控制板雷管数据
     */
    private fun onReadControlData() {
        updateProgress(
            mCurrentDetonatorNum,
            "正在读取控制板雷管信息(${mCurrentDetonatorNum + 1} / $mDetonatorTotalNum)..."
        )
        val number = SerialUtil.getCurrentDetonatorNum(mCurrentDetonatorNum)
        Serials.registerSingleStartHexSerial(CmdCode.KZB_READ_LG_INFO_ASK, object : Serial() {
            override fun loadReceiveData(data: String) {
                if (data.length > 40) {
                    onParesReadControlData(data)
                } else {
                    openKeyDownEvent()
                    updateProgress(-1, "读取控制板雷管信息失败...")
                }
            }
        })
        SerialPortManager.send(CmdCode.KZB_READ_LG_INFO_CMD + number)
    }

    /**
     * 解析控制雷管信息
     */
    private fun onParesReadControlData(data: String) {
        val model = LeiGuanEntity.parse(data)
        getPresenter(ShowDelayDataPresenter::class.java).checkLeiGuanRepeat(model)
        mDetonatorTotalNum = model.total
        checkSendReadNextData()
    }


    /**
     * 检查是否已经到达组网限制
     */
    private fun checkSendReadNextData() {
        if (mCurrentDetonatorNum+1 >= mDetonatorMaxNumLimit) {
            Toll.toll("已达到最大组网数")
            updateProgress(-1, "已达到最大组网数(${mCurrentDetonatorNum+1} / $mDetonatorTotalNum)...")
            (context as DelayActivity).addLog("在线扫描",0,"读控制板数据,最大${mCurrentDetonatorNum}发")
            readControlDataEnd()
            return
        }
        if (mDetonatorTotalNum <= mCurrentDetonatorNum+1) {
            updateProgress(-1, "控制板数据已全部读取完成(${mCurrentDetonatorNum+1} / $mDetonatorTotalNum)...")
            (context as DelayActivity).addLog("在线扫描",0,"读控制板数据,有${mCurrentDetonatorNum+1}发")
            readControlDataEnd()
        } else {
            mCurrentDetonatorNum++
            onReadControlData()
        }
    }

    /**
     * 读雷管信息结束
     */
    private fun readControlDataEnd() {
        getPresenter(ShowDelayDataPresenter::class.java).run {
            refreshData()
            openKeyDownEvent()
            delayShowImportDataPop(mDetonatorTotalNum)
        }
    }

    /**
     * 打开按键限制
     */
    private fun openKeyDownEvent() {
        CJQUpdateModel.isPauseReceive = false
        mKeyDownEvent.isCanBack = true
        LifecycleManager.manager.refreshLiveData(mKeyDownEvent)
    }

    override fun onDestroy() {
        super.onDestroy()
        Serials.unRegisterSingleStartHexSerial(CmdCode.KZB_READ_LG_INFO_ASK)
        Serials.unRegisterSingleStartHexSerial(CmdCode.KZB_QUERY_LG_INFO_OK_ASK)
        Serials.unRegisterSingleStartHexSerial(CmdCode.KZB_SCAN_LG_OK_ASK)
        Serials.unRegisterSingleStartHexSerial(CmdCode.KZB_SCAN_LG_E_ASK)
        Serials.unRegisterSingleStartHexSerial(CmdCode.KZB_CLEAR_STATE_OK_ASK)
        Serials.unRegisterSingleStartHexSerial(CmdCode.KZB_CLEAR_STATE_E_ASK)
    }

}